package com.example.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author ME
 */
@Slf4j
public final class ManifestFileExtractor {
    private static Map<String, String> result = new HashMap<>(16);

    static {
        String jarFilePath = ClassUtils.getDefaultClassLoader()
                .getResource("").getPath().replace("!/BOOT-INF/classes!/", "");
        if (!jarFilePath.endsWith(".jar")) {
            log.warn("Current Running Mode is not a packaged JAR file, ignore the manifest file extracting.");
        } else {
            if (jarFilePath.startsWith("file")) {
                jarFilePath = jarFilePath.substring(5);
            }
            log.info("读取的Jar路径为:{}", jarFilePath);
            try (JarFile jarFile = new JarFile(jarFilePath)) {
                JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF");
                if (null != entry) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(
                                    jarFile.getInputStream(entry), StandardCharsets.UTF_8));
                    String currentLine;
                    String lastLine = "";
                    while (null != (currentLine = reader.readLine())) {
                        log.info("读取到行:{}", currentLine);
                        int i = currentLine.indexOf(':');
                        if (-1 == i) {
                            currentLine = lastLine.trim() + currentLine.trim();
                        }

                        lastLine = "";

                        i = currentLine.indexOf(':');
                        if (i > -1) {
                            lastLine = lastLine.trim() + currentLine.trim();

                            String key = currentLine.substring(0, i).trim();
                            if (key.isEmpty()) {
                                log.warn("Ignore line {} for empty key", currentLine);
                                continue;
                            }
                            String value = currentLine.substring(i + 1).trim();
                            if (value.isEmpty()) {
                                log.warn("Ignore line {} for empty value", currentLine);
                                continue;
                            }
                            result.put(key, value);
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("解析MANIFEST.MF文件异常", e);
            }
        }
    }

    public static Map<String, String> extract() {
        return result;
    }

}
